/*
 * Copyright (C) 2003, Velocityme Partnership
 * DepartmentSessionBean.java
 *
 * Created on 25 August 2003, 05:19
 */

package com.velocityme.session;

import com.velocityme.entity.ChangeDeltaItemTypeBean;
import com.velocityme.entity.ChangeDeltaTypeBean;
import com.velocityme.entity.PermissionBean;
import javax.ejb.*;
import javax.naming.*;
import java.util.*;
import com.velocityme.interfaces.*;
import com.velocityme.utility.InvalidKeyException;
import com.velocityme.utility.PermissionDeniedException;
import com.velocityme.valueobjects.*;
import java.rmi.RemoteException;

/**
 *
 * @author  Robert Crida Work
 * @ejb.bean
 *           type="Stateless"
 *           cmp-version="2.x"
 *           name="DepartmentSession"
 *           jndi-name="ejb/DepartmentSession"
 *           view-type="local"
 *           transaction-type="Container"
 * @ejb.transaction type="Required"
 *
 * @ejb.util generate="physical"
 */
public class DepartmentSessionBean implements SessionBean {
    
    private SessionContext m_context;
    
    private SearchSessionLocal m_searchSessionLocal;

    private PermissionLocal m_permissionDepartmentCreate;
    private PermissionLocal m_permissionDepartmentEdit;
    private PermissionLocal m_permissionNodeView;

    /**
     * If the user has permission to create a new Department in the specified 
     * parentnode then go ahead and create it and log an appropriate ChangeDelta.
     *
     * @param p_key User's security key
     * @param p_parentNode The node which will contain the new Department
     * @param p_departmentValue The value details for the Department part of the department
     *
     * @ejb.interface-method view-type="local"
     **/
    public DepartmentLocal createDepartment(KeySessionLocal p_keyLocal,
                                            NodeLocal p_parentNodeLocal,
                                            com.velocityme.valueobjects.DepartmentValue p_departmentValue) 
        throws PermissionDeniedException, InvalidKeyException {
        try {
            if (m_searchSessionLocal.getAssignedPermissionsLocal(p_keyLocal, p_parentNodeLocal).contains(m_permissionDepartmentCreate)) {
                DBObjectLocal dBObjectLocal = DBObjectUtil.getLocalHome().create();
                ContactableValue contactableValue = p_departmentValue.getContactableValue();
                contactableValue.setType("Department");
                contactableValue.getNodeValue().setFinalType("Department");
                NodeValue nodeValue = contactableValue.getNodeValue();
                nodeValue.setType("Contactable");
                NodeLocal nodeLocal = NodeUtil.getLocalHome().create(dBObjectLocal, nodeValue, p_parentNodeLocal);
                nodeValue.setNodeId(nodeLocal.getNodeId());
                ContactableSessionUtil.getLocalHome().create().calcContactDetailChanges(contactableValue, null);
                ContactableLocal contactableLocal = ContactableUtil.getLocalHome().create(nodeLocal, contactableValue);
                contactableValue.setContactableId(contactableLocal.getContactableId());
                DepartmentLocal departmentLocal = DepartmentUtil.getLocalHome().create(contactableLocal, p_departmentValue);
                ChangeDeltaLocal changeDeltaLocal = ChangeDeltaUtil.getLocalHome().create(new Date(), ChangeDeltaTypeBean.CREATE, p_keyLocal.getUserLocal(), dBObjectLocal);
                changeDeltaLocal.addItem(ChangeDeltaItemTypeBean.NAME, nodeValue.getName());
                changeDeltaLocal.addItem(ChangeDeltaItemTypeBean.DESCRIPTION, nodeValue.getDescription());
                changeDeltaLocal.addItem(ChangeDeltaItemTypeBean.PARENT_NODE, p_parentNodeLocal.getPathName());
                ContactableSessionUtil.getLocalHome().create().addContactDetailDeltas(changeDeltaLocal, contactableValue);
                return departmentLocal;
            }
            else
                throw new PermissionDeniedException();
        }
        catch(NamingException e) {
            throw new EJBException(e);
        }
        catch(CreateException e) {
            throw new EJBException(e);
        }
    }
    
    /**
     * If the user has permission to edit the department then do so and log the
     * changes with an appropriate ChangeDelta.
     *
     * @param p_key User's security key
     * @param p_department The Department object being edited
     * @param p_departmentValue The value details for the Department part of the department
     *
     * @ejb.interface-method view-type="local"
     **/
    public void editDepartment(KeySessionLocal p_keyLocal,
                               DepartmentLocal p_departmentLocal,
                               com.velocityme.valueobjects.DepartmentValue p_departmentValue) 
        throws PermissionDeniedException, InvalidKeyException {
        try {
            ContactableLocal contactableLocal = p_departmentLocal.getContactableLocal();
            NodeLocal nodeLocal = contactableLocal.getNodeLocal();
            if (m_searchSessionLocal.getAssignedPermissionsLocal(p_keyLocal, nodeLocal).contains(m_permissionDepartmentEdit)) {
                ContactableValue contactableValue = p_departmentValue.getContactableValue();
                NodeValue nodeValue = contactableValue.getNodeValue();
                ChangeDeltaLocal changeDeltaLocal = ChangeDeltaUtil.getLocalHome().create(new Date(), ChangeDeltaTypeBean.EDIT, p_keyLocal.getUserLocal(), nodeLocal.getDBObjectLocal());
                if (!nodeValue.getName().equals(nodeLocal.getName()))
                    changeDeltaLocal.addItem(ChangeDeltaItemTypeBean.NAME, nodeValue.getName());
                if (!nodeValue.getDescription().equals(nodeLocal.getDescription()))
                    changeDeltaLocal.addItem(ChangeDeltaItemTypeBean.DESCRIPTION, nodeValue.getDescription());
                ContactableSessionUtil.getLocalHome().create().calcContactDetailChanges(contactableValue, contactableLocal.getContactDetailsLocal());
                ContactableSessionUtil.getLocalHome().create().addContactDetailDeltas(changeDeltaLocal, contactableValue);
                nodeLocal.setNodeValue(nodeValue);
                contactableLocal.setContactableValue(contactableValue);
                p_departmentLocal.setDepartmentValue(p_departmentValue);
            }
            else
                throw new PermissionDeniedException();
        }
        catch(NamingException e) {
            throw new EJBException(e);
        }
        catch(CreateException e) {
            throw new EJBException(e);
        }
    }
    
    /**
     * If the user has permission to access a department then return the local object.
     *
     * @param p_key User's security key
     * @param p_departmentPK The Department object to lookup
     *
     * @ejb.interface-method view-type="local"
     **/
    public DepartmentLocal getDepartmentLocal(KeySessionLocal p_keyLocal, 
                                              DepartmentPK p_departmentPK)
        throws PermissionDeniedException, InvalidKeyException {
        try {
            DepartmentLocal departmentLocal = DepartmentUtil.getLocalHome().findByPrimaryKey(p_departmentPK);
            NodeLocal nodeLocal = departmentLocal.getContactableLocal().getNodeLocal();
            if (m_searchSessionLocal.getAssignedPermissionsLocal(p_keyLocal, nodeLocal).contains(m_permissionNodeView)) {
                return departmentLocal;
            }
            else
                throw new PermissionDeniedException();
        }
        catch(NamingException e) {
            throw new EJBException(e);
        }
        catch(FinderException e) {
            throw new EJBException(e);
        }
    }
    
    /**
     * Get the full list of department value objects.
     *
     * @param p_key User's security key
     *
     * @ejb.interface-method view-type="local"
     **/
    public java.util.Collection getAllValueObjects(KeySessionLocal p_keyLocal) throws InvalidKeyException {
        Collection values = new java.util.ArrayList();
        try {
            if (p_keyLocal.isValid()) {
                Collection departments = DepartmentUtil.getLocalHome().findAll();
                Iterator i = departments.iterator();
                while(i.hasNext()) {
                    DepartmentLocal departmentLocal = (DepartmentLocal)i.next();
                    values.add(new DepartmentValueToString(departmentLocal.getDepartmentValueQualified()));
                }
            }
            else
                throw new InvalidKeyException();
        }
        catch(NamingException e) {
            throw new EJBException(e);
        }
        catch(FinderException e) {
            throw new EJBException(e);
        }
        return values;
    }
    
    /**
     * Create the Session Bean.
     * @throws CreateException 
     */
    public void ejbCreate() throws CreateException {
        try {
            m_searchSessionLocal = SearchSessionUtil.getLocalHome().create();
            m_permissionDepartmentCreate = PermissionUtil.getLocalHome().findByPrimaryKey(new PermissionPK(new Integer(PermissionBean.DEPARTMENT_CREATE)));
            m_permissionDepartmentEdit = PermissionUtil.getLocalHome().findByPrimaryKey(new PermissionPK(new Integer(PermissionBean.DEPARTMENT_EDIT)));
            m_permissionNodeView = PermissionUtil.getLocalHome().findByPrimaryKey(new PermissionPK(new Integer(PermissionBean.NODE_VIEW)));
        }
        catch(NamingException e) {
            throw new CreateException(e.getMessage());
        }
        catch(FinderException e) {
            throw new CreateException(e.getMessage());
        }
    }

    public void ejbActivate() throws java.rmi.RemoteException {
    }
    
    public void ejbPassivate() throws java.rmi.RemoteException {
    }
    
    public void ejbRemove() throws java.rmi.RemoteException {
    }
    
    public void setSessionContext(javax.ejb.SessionContext sessionContext) throws java.rmi.RemoteException {
        m_context = sessionContext;
    }
    
}
